# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import os
from conans import ConanFile, tools, CMake


class AbseilConan(ConanFile):
    name = "abseil"
    description = "Abseil Common Libraries (C++) from Google"
    license = "Apache-2.0"
    settings = "os", "arch", "compiler", "build_type"
    exports_sources = ["permissions.ini"]
    generators = "cmake_find_package_multi"
    _cmake = None
    options = {
        "shared": [True, False],
        "fPIC": [True, False],
        "build_tests": [True, False]
    }
    default_options = {
        "shared": False,
        "fPIC": True,
        "build_tests": False
    }

    @property
    def _source_subfolder(self):
        return "source_subfolder"

    def source(self):
        git = tools.Git(verify_ssl=False)
        git.clone(**self.conan_data["sources"][self.version])

    def build(self):
        cmake = self._configure_cmake()
        cmake.build()

    def package(self):
        cmake = self._configure_cmake()
        cmake.install()
        self.copy("permissions.ini", src="", dst="")

    def package_info(self):
        self.cpp_info.includedirs = ["include"]
        self.cpp_info.libs.extend(tools.collect_libs(self))

    def _configure_cmake(self):
        if self._cmake:
            return self._cmake
        self._cmake = CMake(self)
        if not self.settings.build_type == "Dt":
            os.environ['CXXFLAGS'] = os.getenv('CXXFLAGS') + ' -march=armv8-a+crypto'
        os.environ['CFLAGS'] = os.getenv('CFLAGS') + " -D_FORTIFY_SOURCE=2 -Os"
        os.environ['CXXFLAGS'] = os.getenv('CXXFLAGS') + " -D_FORTIFY_SOURCE=2 -Os"
        self._cmake.definitions["ABSL_ENABLE_INSTALL"] = "ON"
        self._cmake.definitions["BUILD_SHARED_LIBS"] = self.options.shared
        self._cmake.definitions["CMAKE_CXX_STANDARD"] = 17
        self._cmake.definitions["BUILD_TESTING"] = "OFF"
        self._cmake.definitions["CMAKE_POSITION_INDEPENDENT_CODE"] = self.options.fPIC
        self._cmake.configure(args=["--no-warn-unused-cli"])
        return self._cmake